export const BaseURL = 'http://localhost:3000';

// 获取聊天流数据接口
export const getChatFlowList = () => {
    return fetch(`${BaseURL}/api/v1/chatflows`).then(async (res) => {
        const records: any[] = await res.json();
        const flowDataImages = (flowDataStr: string) => {
            const flowData = JSON.parse(flowDataStr);
            const nodes = flowData.nodes || [];
            return nodes.map((item: any) => `${BaseURL}/api/v1/node-icon/${item.data.name}`);
        }
        return records.map(i => {
            return {
                ...i,
                categoryList: i.category?.split(';') || [],
                nodeImageList: flowDataImages(i.flowData)
            }
        });
    });
}
// 获取所有节点列表
export const getChatFlowInfo = (id: string) => {
    return fetch(`${BaseURL}/api/v1/chatflows/${id}`).then(async (res) => {
        const data: any = await res.json();
        return {
            ...data,
            iconUrl: `${BaseURL}/api/v1/node-icon/${data.name}`
        }
    });
}

// 新增
export const addChatFlow = (data: any) => {
    return fetch(`${BaseURL}/api/v1/chatflows`, {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
            'content-type': 'application/json'
        },
    }).then((res) => res.json());
}

// 更新
export const updateChatFlow = (data: any) => {
    return fetch(`${BaseURL}/api/v1/chatflows/${data.id}`, {
        method: 'PUT',
        body: JSON.stringify(data),
        headers: {
            'content-type': 'application/json'
        },
    }).then((res) => res.json());
}

// 删除
export const deleteChatFlow = (id: string) => {
    return fetch(`${BaseURL}/api/v1/chatflows/${id}`, { method: 'DELETE' }).then((res) => res.json());
}

// 获取所有节点列表
export const getNodes = () => {
    return fetch(`${BaseURL}/api/v1/nodes`).then(async (res) => {
        const records: any[] = await res.json();
        return records.map(i => {
            return {
                ...i,
                iconUrl: `${BaseURL}/api/v1/node-icon/${i.name}`
            }
        });
    });
}

// 节点信息加载方法
export const requestNodeLoadMethod = ({ loadMethod, name = 'chatOpenAI' }: any) => {
    const data = { loadMethod }
    return fetch(`${BaseURL}/api/v1/node-load-method/${name}`, {
        method: 'POST',
        body: JSON.stringify(data),
        cache: 'default', // default, no-cache, reload, force-cache, only-if-cached
        // credentials: 'same-origin', // include, same-origin, *omit
        headers: {
            'content-type': 'application/json'
        },
    }).then((res) => res.json());
}

// 获取凭证列表
export const getCredentials = (name: string) => {
    return fetch(`${BaseURL}/api/v1/credentials?credentialName=${name}`).then((res) => res.json());
}